/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.listener;

import com.bifrost.entity.Order;
import com.bifrost.entity.ProductSku;
import com.bifrost.event.OrderSubmittedEvent;
import com.bifrost.service.OrderService;
import com.bifrost.service.OrderStatusHistoryService;
import com.bifrost.service.ProductSkuService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/27 19:33
 */
@Component
public class OrderSubmittedListener implements ApplicationListener<OrderSubmittedEvent> {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Value("${template.Message.submitOrder:#{null}}")
    private String templateId;
    @Value("${view.order.url:#{null}}")
    private String viewOrderUrl;
    @Autowired
    OrderService orderService;
    @Autowired
    ProductSkuService productSkuService;
    //@Autowired
    WxMpTemplateMsgService wxMpTemplateMsgService;
    @Autowired
    OrderStatusHistoryService statusHistoryService;
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderSubmittedListener.class);

    @Override
    public void onApplicationEvent(OrderSubmittedEvent orderSubmittedEvent) {
        Long orderId = orderSubmittedEvent.getOrderId();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("订单：%d，编号%s已经提交", orderId, orderSubmittedEvent.getOrderNumber()));
        }
        Order order = orderService.findOrderById(orderId);
        if (order != null) {
            //增加销售数量
            statusHistoryService.writeHistory(order, String.format("提交成功"), Boolean.TRUE,null);
            order.getOrderItems().stream().forEach(orderItem -> {
                ProductSku defaultSku = productSkuService.getDefaultSku(orderItem.getSkuId());
                if(defaultSku != null){
                    productSkuService.incrementSalesQuantity(defaultSku.getSkuId(), orderItem.getSkuQuantity());
                }
            });
        }
    }

}
